package com.qianniu.napi.admin.web;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.google.common.base.Strings;
import com.qianniu.napi.admin.entity.Jinfo;
import com.qianniu.napi.admin.entity.Resource;
import com.qianniu.napi.admin.service.IResourceService;
import com.qianniu.napi.common.config.Constants;
import com.qianniu.napi.common.util.ObjectUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.io.File;
import java.util.Date;

/**
 * <p>
 * 素材管理
 * </p>
 *
 * @author chenxuebin
 * @since 2018-10-22
 */
@RestController
public class ResourceController {

    private static final Logger logger = LoggerFactory.getLogger(ResourceController.class);

    @Autowired
    private IResourceService resourceService;

    //    @RequestMapping("/api/resource/list")
//    @ResponseBody
//    public Jinfo list(@RequestParam(value = "status", required = false) String status,
//                      @RequestParam(value = "pageIndex", required = false) Integer pageIndex,
//                      @RequestParam(value = "pageSize", required = false) Integer pageSize,
//                      HttpServletRequest req) {
//        Jinfo info = new Jinfo();
//        if (pageSize == null) pageSize = 10;
//        Page page = new Page(pageIndex, pageSize);
//        page = resourceService.selectPage(page, new EntityWrapper<Resource>()
//                .eq("uid", ObjectUtil.getUid())
//                .eq("state", 1));
//        info.setInfo(page.getRecords());
//        return info;
//    }
    @RequestMapping("/api/resource/list")
    @ResponseBody
    public Jinfo resourceList(Integer rtype,
                              @RequestParam(value = "pageIndex", required = false) Integer pageIndex,
                              @RequestParam(value = "pageSize", required = false) Integer pageSize) {
        Jinfo info = new Jinfo();

        Page page = new Page(pageIndex, pageSize);
        Wrapper<Resource> entity = new EntityWrapper<Resource>().eq("mpid", ObjectUtil.getMpid());
        if (ObjectUtil.getSid() != null) {
            entity.eq("sid", ObjectUtil.getSid());
        }
        if (rtype != null) {
            entity.eq("rtype", rtype);
        }
        entity.orderBy("id");
        Page<Resource> fs1 = resourceService.selectPage(page, entity);
        info.setInfo(fs1.getRecords());
        return info;
    }

    @RequestMapping("/api/resource/add")
    @ResponseBody
    public Jinfo resourceAdd(@Valid Resource resource,
                             BindingResult bindingResult, HttpServletRequest req) {
        Jinfo info = new Jinfo();
        // 字段校验
        if (bindingResult.hasErrors()) {
            logger.debug("There are errors! {}", bindingResult);
            info.setMsg("There are errors! " + bindingResult);
            info.setCode(400);
            return info;
        }
        resource.setCreatetime(new Date());
        resource.setMid(ObjectUtil.getMid());
        resource.setMpid(ObjectUtil.getMpid());
        resource.setUid(ObjectUtil.getUid());
        resource.insert();
        return info;
    }

    @RequestMapping("/api/resource/modify")
    @ResponseBody
    public Jinfo resourceUpdate(HttpServletRequest req,
                                Resource resource) {
        Jinfo info = new Jinfo();
        resource.setModifytime(new Date());
        resource.updateById();
        return info;
    }

    @RequestMapping("/api/resource/detail")
    @ResponseBody
    public Jinfo getResourceDetailById(@RequestParam("token") String token,
                                       @RequestParam("id") long id, HttpServletRequest req
    ) {
        Jinfo info = new Jinfo();
        Resource resource = resourceService.selectById(id);
        info.setInfo(resource);
        return info;
    }

    @RequestMapping("/api/resource/del")
    @ResponseBody
    public Jinfo delResource(@RequestParam("id") long id) {
        Jinfo info = new Jinfo();
        Resource resource = resourceService.selectById(id);
        String pic = resource.getPic();
        String path = pic.replace(Constants.IMG_UPLOAD_HOST, Constants.PATH_IMAGES);
        String thumbpath = null;
        if (Strings.isNullOrEmpty(resource.getThumb())) {
            thumbpath = pic.replace(Constants.IMG_UPLOAD_HOST, Constants.PATH_IMAGES);
        }

        //删除本地视频文件+其他文件
        try {
            File file = new File(path);
            file.delete();

            //缩略图
            if (thumbpath != null) {
                File thumbfile = new File(thumbpath);
                thumbfile.delete();
            }
        } catch (Exception e) {
            logger.error("-------------delResource error", e);
        }

        resourceService.deleteById(id);
        return info;
    }

}
